package com.lefevre.cms.web.action.common;


import com.lefevre.cms.bean.theme.Forum;
import com.lefevre.cms.bean.theme.Layout;
import com.lefevre.cms.bean.theme.ThemeRunObject;
import com.lefevre.cms.service.theme.ThemeService;
import com.lefevre.cms.utils.JsonUtils;
import com.lefevre.cms.utils.WebUtil;
import com.lefevre.cms.utils.threadLocal.TemplateThreadLocal;
import com.lefevre.cms.web.action.AccessDeviceUtil;
import com.lefevre.cms.web.action.theme.TemplateMain;
import org.apache.commons.lang3.StringUtils;
import org.queryString.util.MultiMap;
import org.queryString.util.UrlEncoded;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * 根据相应的URI读取相关'空白页'
 * 由cms.web.filter.WebConfig.java调用
 */
@Controller("blankAction")
public class BlankAction extends AbstractController {
    @Resource
    TemplateMain templateMain;//模板管理入口
    @Resource
    AccessDeviceUtil accessDeviceUtil;
    @Resource(name = "themeServiceImpl")
    private ThemeService themeService;

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //String path = request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString();


        // 判断Url并分发到不同的Action，并统一控制转向
        String currentURI = request.getRequestURI();//获取当前的全部URI
        String dirName = themeService.findTemplateDir_cache();

        String accessPath = accessDeviceUtil.accessDevices(request);

        if (currentURI != null && !"".equals(currentURI)) {
            String paths = request.getContextPath();//系统虚拟路径
            if (paths != null && !"".equals(paths)) {
                currentURI = StringUtils.substringAfter(currentURI, paths);//删除系统虚拟路径
            }
            String URI = StringUtils.substringAfter(currentURI, "/");
            URI = StringUtils.substringBeforeLast(URI, ".");


            Map<String, Object> parameter = this.getQueryString(request.getQueryString());//获取URL参数

            String templatesDir = themeService.findTemplateDir_cache();
            List<Layout> layoutList = themeService.findLayout_cache(templatesDir, 4);//4.空白页
            for (Layout layout : layoutList) {

                if (URI != null && !"".equals(URI)) {

                    if (URI.toLowerCase().equals(layout.getReferenceCode().toLowerCase())) {

                        if (layout.getReturnData().equals(0)) {//返回数据为html方式
                            response.setHeader("Pragma", "No-cache");
                            response.setHeader("Cache-Control", "no-cache,no-store,max-age=0");
                            response.setDateHeader("Expires", 1);

                            //去掉.ftl后缀
                            String layouts = StringUtils.substringBefore(layout.getLayoutFile(), ".");//返回指定字符串之前的所有字符
                            return new ModelAndView("/templates/" + layout.getDirName() + "/" + accessPath + "/public/" + layouts);
                        } else {//返回数据为json方式


                            Map<String, Object> runtimeParameter = new HashMap<>();//运行时参数
                            ThemeRunObject themeRunObject = TemplateThreadLocal.get();
                            if (themeRunObject != null && themeRunObject.getRuntimeParameter() != null && themeRunObject.getRuntimeParameter().size() > 0) {
                                runtimeParameter.putAll(themeRunObject.getRuntimeParameter());
                            }

                            List<Forum> forumList = themeService.findForumByLayoutId_cache(templatesDir, layout.getId());
                            for (Forum forum : forumList) {
                                Object obj = templateMain.templateObject(forum, parameter, runtimeParameter);
                                if (obj != null) {
                                    WebUtil.writeToWeb(JsonUtils.toJSONString(obj), "json", response);
                                } else {
                                    WebUtil.writeToWeb("", "json", response);

                                }

                                return null;
                                //json方式只有一个版块有效
                                //	break;
                            }
                            //如果没添加版块则返回null
                            return null;
                        }
                    }
                }
            }
        }


        //UserRoleManage类在检查权限时可能会返回message内容
        Object parameter = request.getAttribute("message");
        if (parameter == null) { //如果上一环节没有传递参数
            request.setAttribute("message", "页面不存在");//返回消息
        }

        return new ModelAndView("/templates/" + dirName + "/" + accessPath + "/message");
    }


    /**
     * 获取url参数
     *
     * @param queryString
     * @return
     */
    private Map<String, Object> getQueryString(String queryString) {
        Map<String, Object> parameter = new HashMap<>();//参数

        if (queryString != null && !"".equals(queryString)) {
            MultiMap<String> values = new MultiMap<>();
            UrlEncoded.decodeTo(queryString, values, "UTF-8");

            Iterator iter = values.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry e = (Map.Entry) iter.next();
                if (e.getValue() != null) {


                    if (e.getValue() instanceof List) {

                        List<String> valueList = (List) e.getValue();

                        if (valueList.size() > 0) {
                            for (String value : valueList) {
                                if (value != null && !"".equals(value.trim())) {
                                    parameter.put(e.getKey().toString(), value);
                                }
                                break;
                            }
                            /**
                             if(valueList.size() ==1){//字符类型参数
                             for(String value :valueList){
                             if(value != null && !"".equals(value.trim())){
                             parameter.put(e.getKey().toString(), value);
                             }
                             }

                             }else{//集合类型参数
                             List<String> parameterValueList = new ArrayList<>();
                             for(String value :valueList){
                             if(value != null && !"".equals(value.trim())){
                             parameterValueList.add(value);
                             }
                             }
                             parameter.put(e.getKey().toString(), parameterValueList);
                             }**/

                        }
                    }
                }
            }
        }

        return parameter;
    }


}
